package cn.tedu.straw.api.question.controller;



import cn.tedu.straw.api.question.message.PostQuestionMessage;
import cn.tedu.straw.api.question.service.IQuestionService;
import cn.tedu.straw.api.question.vo.QuestionListItemVO;
import cn.tedu.straw.commons.dto.PostQuestionDTO;
import cn.tedu.straw.commons.ex.FileEmptyException;
import cn.tedu.straw.commons.ex.FileSizeException;
import cn.tedu.straw.commons.ex.FileTypeException;
import cn.tedu.straw.commons.ex.ParamValidationException;
import cn.tedu.straw.commons.model.Question;
import cn.tedu.straw.commons.security.LoginUserInfo;
import cn.tedu.straw.commons.util.R;
import cn.tedu.straw.commons.vo.QuestionSimpleListItemVO;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-02-26
 */
@Slf4j
@RestController
@RequestMapping("/v1/question")
public class QuestionController {
    @Value("${project.fileupload.question-image.base-dir}")
    String uploadBaseDir;
    @Value("${project.fileupload.question-image.max-size}")
    long uploadMaxSize;
    @Value("${project-fileupload.question-image.content-types}")
    List<String> contentTypes;
    @Autowired
    IQuestionService questionService;
    @Autowired(required = false)
    KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    Gson gson;
    //在QuestionController的post方法中,原本接受到的请求后是直接通过Service组件来发布问题的,改为向kafka发送消息:
    @RequestMapping("/post")
    public R post(@Valid PostQuestionDTO postQuestionDTO,
                  BindingResult bindingResult,
                  @AuthenticationPrincipal LoginUserInfo loginUserInfo){

        if(bindingResult.hasErrors()){
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            throw new ParamValidationException(errorMessage);
        }
        Integer userId = loginUserInfo.getId();
        String userNickName = loginUserInfo.getNickName();
        PostQuestionMessage postQuestionMessage = new PostQuestionMessage();
        postQuestionMessage.setPostQuestionDTO(postQuestionDTO);
        postQuestionMessage.setUserId(userId);
        postQuestionMessage.setUserNickName(userNickName);
        String data = gson.toJson(postQuestionMessage);
        kafkaTemplate.send("POST_QUESTION",data);
        //questionService.post(postQuestionDTO,userId,userNickName);
        return R.ok();
    }


    @GetMapping("/my")
    public R<PageInfo<QuestionListItemVO>> getMyQuestions(@AuthenticationPrincipal  LoginUserInfo loginUserInfo, Integer page){
        if(page == null || page < 1){
            page = 1;
        }
        Integer userId = loginUserInfo.getId();
        PageInfo<QuestionListItemVO> pageInfo = questionService.getMyQuestions(userId,page);
        System.out.println(pageInfo);
        return R.ok(pageInfo);
    }

 //http://localhost:8080/portal/question/most-hits

        @GetMapping("/most-hits")
        public R<List<QuestionSimpleListItemVO>> getMostHitsList(){
            return R.ok(questionService.getMostHitList());
        }

//    @PostMapping("/upload-image")
//    public R uploadImage(MultipartFile imageFile) {
//        //检查上传文件是否为空
//        if(imageFile.isEmpty()){
//            throw new FileEmptyException("上传图片失败!请选择有效的图片文件");
//        }
//        //检查上传文件的大小
//        if(imageFile.getSize() > uploadMaxSize){
//            throw new FileSizeException("上传图片失败!不允许上传超过" + uploadMaxSize / 1024 + "KB的文件!");
//        }
//        //检查上传的文件类型
//        if(!contentTypes.contains(imageFile.getContentType())){
//            throw new FileTypeException("上传图片失败!允许上传的图片类型有："+contentTypes);
//        }
//        //保存上传时使用的文件夹
//        String yearAndMonth = DateTimeFormatter.ofPattern("yyyy/MM").format(LocalDate.now());
//        File parent = new File(uploadBaseDir,yearAndMonth);
//        if(!parent.exists()){
//            parent.mkdirs();
//        }
//
//        //保存上传文件时使用文件夹
//        String filename = System.currentTimeMillis() + "_" +System.nanoTime();
//        String originalFilename = imageFile.getOriginalFilename();
//        int beginIndex = originalFilename.lastIndexOf(".");
//        String suffix = originalFilename.substring(beginIndex);
//        String child =filename + suffix;
//
//        //保存上传文件的File对象
//        File dest = new File(parent, child);
//        //执行保存
//        try {
//            imageFile.transferTo(dest);
//        }catch (IOException e){
//            e.printStackTrace();
//        }
//        //响应
//        String url ="http://localhost:8080/" + yearAndMonth + "/" +child;
//        System.out.println("url="+url);
//        return R.ok(url);
//    }


//    //http://localhost:8080/portal/question/10
//    @GetMapping("/{id}")
//    public R<Question> getQuestionDetails(@PathVariable("id") Integer id){
//        Question question = questionService.getQuestionDetails(id);
//        return R.ok(question);
//    }
}
